package system

import (
	"errors"
	"fmt"
	"k8s-admin/dao/system"
	"k8s-admin/global"
	"k8s-admin/models"
)

type UserInterface interface {
	List(Limit, Page int) (*models.UserList, error)
	Create(username, password, Phone, Email string, roles []uint, status, dept_id uint) (*models.User, error)
	Delete(UID string) error
	Update(uid, username, password, email, phone string, status uint, roles_id []uint) error
	GetUserFromUserName(uid string) (*models.User, error) // 用户权限查询
	SetUserRole(roleID []uint, uid string) error
	DeleteUserRole(roleID []uint, uid string) error
}

type User struct{}

func NewUserInterface() UserInterface {
	return &User{}
}

func (u *User) List(Limit, Page int) (*models.UserList, error) {
	list, err := system.NewUsersInterface().List(Limit, Page)
	if err != nil {
		global.TPLogger.Error(err.Error())
		return nil, errors.New("占无数据")
	} else {
		return list, nil
	}
}

func (u *User) Create(username, password, Phone, Email string, roles []uint, status, dept_id uint) (*models.User, error) {
	list, err := system.NewUsersInterface().Create(username, password, Phone, Email, roles, status, dept_id)
	if err != nil {
		global.TPLogger.Error(err)
		return nil, errors.New("添加用户失败")
	} else {
		return list, nil
	}
}

func (u *User) Delete(UID string) error {
	err := system.NewUsersInterface().Delete(UID)
	if err != nil {
		global.TPLogger.Error(err.Error())
		return errors.New("删除用户失败")
	} else {
		return nil
	}
}
func (u *User) Update(uid, username, password, email, phone string, status uint, roles_id []uint) error {
	err := system.NewUsersInterface().Update(uid, username, password, email, phone, status, roles_id)
	if err != nil {
		global.TPLogger.Error(err.Error())
		return errors.New("更新用户数据失败")
	} else {
		return nil
	}
}

// 用户权限查询
func (u *User) GetUserFromUserName(uid string) (*models.User, error) {
	NewUser, err := system.NewUsersInterface().GetUserFromUserName(uid)
	if err != nil {
		global.TPLogger.Error(err)
		return nil, err
	} else {
		return NewUser, nil
	}
}

func (u *User) SetUserRole(roleID []uint, uid string) error {
	err := system.NewUsersInterface().SetUserRole(roleID, uid)
	if err != nil {
		global.TPLogger.Error(fmt.Sprintf("角色添加失败: %s\n", err.Error()))
		return errors.New("角色添加失败")
	} else {
		return nil
	}

}

func (u *User) DeleteUserRole(roleID []uint, uid string) error {
	err := system.NewUsersInterface().DeleteUserRole(roleID, uid)
	if err != nil {
		global.TPLogger.Error(fmt.Sprintf("角色删除失败: %s\n", err.Error()))
		return errors.New("角色删除失败")
	} else {
		return nil
	}
}
